<?php

namespace App\Models\CacheModel\consult;

use App\Models\Api\BaseCache;
use AstroTool\Cache\CacheManage;

class AppUserConsultGift extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_user_consult_gift';

    protected $cacheModel = 'user.voice_consult_gift';


    /**
     * 新增 用户礼包
     * @param $data
     * @return int
     */
    public function saveData($data)
    {
        try
        {
            $id = $this->insertGetId($data);

            $this->listDataAdd($data['uid'], [$id => $id], 1);
            CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('user_pay_gift_num', $data['uid'])->rmCache('user_pay_gift_num');
            return (int)$id;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return 0;
        }
    }

    /**
     * 更新 用户礼包信息
     * @param int $uid
     * @param int $id
     * @param array $data
     * @return bool
     */
    public function updateData(int $uid, int $id, array $data)
    {
        try
        {
            $this->where(['id' => $id])->update($data);

            if (isset($data['status']) && in_array($data['status'], [2, 3], true))
            {
                $this->listDataDel($uid, [$id], 1);
                CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->setListKeyType(2)->rmCache('list');
            }

            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->setCache($data);
            return true;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
    }


    /**
     * 开启了缓存
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|string
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            if ($ids)
            {
                $this->whereIn('id', $ids);
            } else
            {
                $this->where(['uid' => $type[0]]);
                if ($type[1] == 1)
                {
                    $this->where(['status' => 1])->order('id ' . $sortType);
                } else
                {
                    $this->where(['status' => ['in', [2, 3]]])->order("update_time {$sortType},id desc");
                }
            }

            $questionResult = $this->order('id ' . $sortType)
                ->column('uid,status,gift_id,unit_price,start_time,end_time,duration_minute,use_minute,order_num,type,create_time,update_time', 'id');
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return [];
        }

        return $questionResult;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'status', 'uid', 'gift_id', 'unit_price', 'start_time', 'end_time', 'duration_minute', 'use_minute', 'type', 'create_time', 'update_time']);
        }
        return $data;
    }

    /**
     * 获取 用户购买 礼包数量
     * @param int $uid
     * @return array
     * @throws \Exception
     */
    public function getUserPayGiftNum(int $uid)
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('user_pay_gift_num', $uid)
            ->getDataAndSet(function () use ($uid)
            {
                try
                {
                    $d = $this->where(['uid' => $uid, 'type' => 1])->group('gift_id')->column('count(*) as num', 'gift_id');
                    if ($d)
                    {
                        return $d;
                    } else
                    {
                        return [0 => 0];
                    }
                }
                catch (\Exception $e)
                {
                    return [0 => 0];
                }
            }, [], 'user_pay_gift_num');

        $resData = [];
        foreach ($data as $giftId => $num)
        {
            if ($giftId)
            {
                $resData[$giftId] = (int)$num;
            }
        }

        return $resData;
    }

    /**
     * 分页 数据重组
     * @param array $dataList
     * @return array
     * @throws \Exception
     */
    public function resertPageDataList(array $dataList)
    {
        $appConsultGiftModel = new AppConsultGift();
        $consultGiftList = [];
        $resData = [];
        foreach ($dataList as $dataItem)
        {
            if (isset($consultGiftList[$dataItem['gift_id']]))
            {
                $consultGiftInfo = $consultGiftList[$dataItem['gift_id']];
            } else
            {
                $consultGiftInfo = $appConsultGiftModel->getInfoById($dataItem['gift_id'], ['name', 'img', 'exclude_astrs', 'minute', 'expiration_time']);
                $consultGiftList[$dataItem['gift_id']] = $consultGiftInfo;
            }

            if (empty($consultGiftInfo['exclude_astrs']))
            {
                $tags = ['不限咨询师'];
            } else
            {
                $tags = ['限部分咨询师'];
            }
            if ($consultGiftInfo['expiration_time'] > 0)
            {
                $tags[] = sprintf("有效期：%d天", $consultGiftInfo['expiration_time']);
            }

            switch ($dataItem['status'])
            {
                case 1:
                    $desc = sprintf("剩余时长：%d分钟", $dataItem['duration_minute'] - $dataItem['use_minute']);
                    if ($dataItem['end_time'] > 0)
                    {
                        $desc .= sprintf("(有效期至%s)", date('Y.m.d', $dataItem['end_time']));
                    }
                    break;
                case 2:
                    $desc = '已用尽';
                    break;
                case 3:
                    $desc = sprintf("已过期(有效期至%s)", date('Y.m.d', $dataItem['end_time']));
                    break;
                default:
                    $desc = '';
            }
            $resData[] = [
                'img' => $consultGiftInfo['img'],
                'title' => $consultGiftInfo['name'],
                'duration_desc' => sprintf("时长%d分钟", $consultGiftInfo['minute']),
                'tags' => $tags,
                'desc' => $desc,
                'gift_id' => $dataItem['id'],
            ];
        }
        return $resData;
    }

    /**
     * 礼包详情 重新组合
     * @param array $userGiftPackInfo
     * @return array
     */
    public function resertGiftPackInfo(array $userGiftPackInfo)
    {
        $appConsultGiftModel = new AppConsultGift();
        $consultGiftInfo = $appConsultGiftModel->getInfoById($userGiftPackInfo['gift_id']);

        if (empty($consultGiftInfo['exclude_astrs']))
        {
            $tags = ['不限咨询师'];
        } else
        {
            $tags = ['限部分咨询师'];
        }
        if ($consultGiftInfo['expiration_time'] > 0)
        {
            $tags[] = sprintf("有效期：%d天", $consultGiftInfo['expiration_time']);
        }
        $remainingTime = $userGiftPackInfo['duration_minute'] - $userGiftPackInfo['use_minute'];
        if ($userGiftPackInfo['end_time'] > 0)
        {
            $desc = sprintf("剩余时长：%d分钟(有效期至%s)", $remainingTime, date('Y.m.d', $userGiftPackInfo['end_time']));
        } else
        {
            $desc = sprintf("剩余时长：%d分钟", $remainingTime);
        }

        $usePageData = (new AppUserConsultGiftUseRecord())->getListPage($userGiftPackInfo['id'], 'id', [], 0, 'asc');
        $useList = [];
        foreach ($usePageData['data'] as $dataItem)
        {
            $useList[] = [
                'create_time' => date('Y-m-d H:i', $dataItem['use_time']),
                'target' => 'local',
                'link' => "chat_order_detail?id={$dataItem['chat_detail_id']}&need_auth=2",
                'btn_name' => '连线详情',
            ];
        }
        return [
            'img' => $consultGiftInfo['img'],
            'title' => $consultGiftInfo['name'],
            'duration_desc' => sprintf("时长%d分钟", $consultGiftInfo['minute']),
            'tags' => $tags,
            'intro' => $appConsultGiftModel->getConsultGiftIntroStr($consultGiftInfo['notice'], 2),
            'status' => $userGiftPackInfo['status'],
            'remaining_time' => $remainingTime,
            'use_list' => $useList,
            'use_range' => empty($consultGiftInfo['exclude_astrs']) ? 0 : 1,
            'id' => $userGiftPackInfo['gift_id'],
            'desc' => $desc,
        ];
    }

    /**
     * 设置 最近购买礼包 的用户信息
     * @param array $data ['id'=>用户礼包ID,'nickname' => '用户昵称'，‘uid’ => '用户uid'，‘gift_id’ =>'礼包商品ID']
     * @return void
     * @throws \RedisException
     */
    public function setRecentPayGiftUserInfo(array $data)
    {
        $redis = CacheManage::getInstance()->redisHandler;
        $cacheKey = 'consult_gift:recent_pay_gift_user_info:info';
        $num = $redis->lLen($cacheKey);
        if ($num >= 15)
        {
            $redis->rPop($cacheKey);
        }

        $redis->lPush($cacheKey, json_encode($data, JSON_UNESCAPED_UNICODE));
    }

    /**
     * 获取 最近购买礼包 的用户信息
     * @return array
     * @throws \RedisException
     */
    public function getRecentPayGiftUserInfo()
    {
        $redis = CacheManage::getInstance()->redisHandler;
        $cacheKey = 'consult_gift:recent_pay_gift_user_info:info';

        if ($redis->exists($cacheKey))
        {
            $data = $redis->lRange($cacheKey, 0, -1);
            foreach ($data as $k => $datum)
            {
                $data[$k] = json_decode($datum, true);
            }
        } else
        {
            $data = $this->alias('g')->join('wechat_backup_07_18_14_43_00.app_user u', 'u.id=g.uid')->where(['g.type' => 1])->order('g.id desc')->limit(15)->column('u.nickname,g.uid,gift_id', 'g.id');
            if ($data)
            {
                foreach ($data as $datum)
                {
                    $redis->lPush($cacheKey, json_encode($datum, JSON_UNESCAPED_UNICODE));
                }
            } else
            {
                $redis->lPush($cacheKey, '[]');
            }
        }

        $appConsultGiftModel = new AppConsultGift();
        $giftInfo = [];
        $resData = [];
        foreach ($data as $datum)
        {
            if (empty($datum))
            {
                continue;
            }
            if (isset($giftInfo[$datum['gift_id']]))
            {
                $consultGiftInfo = $giftInfo[$datum['gift_id']];
            } else
            {
                $consultGiftInfo = $appConsultGiftModel->getInfoById($datum['gift_id'], ['name']);
                $giftInfo[$datum['gift_id']] = $consultGiftInfo;
            }

            if (mb_strlen($datum['nickname']) > 4)
            {
                $datum['nickname'] = mb_substr($datum['nickname'], 0, 4) . '*';
            }

            $resData[] = sprintf("%s购买了%s", $datum['nickname'], $consultGiftInfo['name']);
        }

        return $resData;
    }
}
